import 'dart:async';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:smart_translator/app/beans/transcript_item_model.dart';
import 'package:smart_translator/app/db/DbDAOHelper.dart';
import 'package:smart_translator/app/event/DataCallBack.dart';
import 'package:smart_translator/app/modules/home/controllers/home_controller.dart';
import '../../db/database.dart';
import '../../manager/AudioStreamManager.dart';
import '../../nets/NetWorkManager.dart';
import '../../routes/app_pages.dart';
import '../../style/widget_style.dart';

import '../../utils/CommonUtil.dart';
import '../../utils/tips.dart';
import '../../services/AudioService.dart';


class RecordTranscriptViewRecordingController extends GetxController {

  var hasTranScript = false.obs;

  var speaker_person = ''.obs;
  var offset_time = ''.obs;

  int conversationSequence = 0;
  var currentSpeaker = ''.obs;

  String? sessionId;
  String? audioType;

  TranscriptItem? currentTranscriptItem;
  TranscriptItem? currentTmpTranscriptItem;

  var globalDuration = 0.obs;

  var session = Session(id: 0, user_id: 0, folder_id: 0, audio_length: 0,
      session_name: '', s_name: '', s_type: '', has_read: false,
      audio_path: '', audio_size: '',
      create_time: DateTime.now(), update_time: DateTime.now()).obs;


  RxList<AudioTranscriptDataExtends> audioTranscriptSource = RxList<AudioTranscriptDataExtends>();

  RxList<Widget> chatList = RxList<Widget>();


  RecordTranscriptViewRecordingController(this.sessionId, this.audioType);

  ScrollController chatListScrollController = ScrollController();

  bool audioStop = false;

  AudioService audioService = Get.find<AudioService>();

  var fromLanguage = ''.obs;
  var finalFromLanguage = ''.obs;
  var tempFromLanguage = ''.obs;

  int finishCount = 0;
  int contentLength = 0;

  RxList<double> amplitudes = RxList.filled(50, 100.00);
  Timer? _audioWavetimer;


  var transcriptDisplayFromLanguage = '中'.obs;
  String transcriptFromLanguageCode = 'zh-CN';

  var script_edit_mode = false.obs;

  AudioTranscriptDataExtends? checkedAudioTranscript;

  var editingStatus = false.obs;
  final scriptController = TextEditingController();

  @override
  void onInit() {
    super.onInit();

    currentTmpTranscriptItem = TranscriptItem(offset: 0,duration: 0);

    if (audioType == 'new') {
      audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP + NetWorkManager.SPEECH_RECOGNITION}?enableSpeaker=1',
          DataCallBack(
            sessionCallBack: (params) {
              handlerSessionData(params);
            },
            deviceCallBack: (v) {
               DbDAOHelper().updateSessionAudioPathById(int.parse(sessionId!), audioService.audioFilePath);
               simulateAudioData();
               audioService.record();
            }
          ));

    } else {
      DbDAOHelper().obtainSessionBySessionId(int.parse(sessionId!)).then((sessions) {

        if (sessions.isNotEmpty) {
          session.value = sessions[0];

          audioService.recordShowSeconds.value = CommonUtil.formatMillisecondsToHHMMSS(session.value.audio_length);
          print('session.length:: ${session.value.audio_length}, ${audioService.recordShowSeconds.value}');
          //查询转写脚本.
          DbDAOHelper().obtainTranscriptsBySessionId(int.parse(sessionId!)).then((transcripts) {
            transcripts.forEach((scriptData) {
              AudioTranscriptDataExtends audioExtends = AudioTranscriptDataExtends(id: scriptData.id, session_id: scriptData.session_id,
                  chat_sequence: scriptData.chat_sequence,
                  m_id: scriptData.m_id,
                  a_text: scriptData.a_text,
                  duration: scriptData.duration,
                  offset: scriptData.offset,
                  speaker: scriptData.speaker,
                  create_time: scriptData.create_time,
                  update_time: scriptData.update_time);

              audioTranscriptSource.add(audioExtends);
              });

            if (audioTranscriptSource.isEmpty) {
              hasTranScript.value = false;
            } else {
              hasTranScript.value = true;
            }

          });
        }
      });


    }

  }




  void handlerSessionData(Map result) {
    // 服务器转写结果.
    if(result['finish'] == true) {
      // fromLanguage.value = fromLanguage.value + result['text'];
      finishCount = finishCount + 1;
      // finalFromLanguage.value = fromLanguage.value;
      print('finalFromLanguage.value.length :: ${finalFromLanguage.value.length}');
      // if (result['speaker'] != 'Unknown' && currentSpeaker.value != result['speaker']) {
      if ((currentSpeaker.value != result['speaker'] && currentSpeaker.value != 'Unknown') || finalFromLanguage.value.length > 150) {
        // currentSpeaker.value = result['speaker'];
        conversationSequence =  conversationSequence + 1;

        currentTranscriptItem = TranscriptItem(offset: 0,duration: 0);
        currentTranscriptItem!.text = finalFromLanguage.value;
        currentTranscriptItem!.speaker = currentSpeaker.value;
        currentTranscriptItem!.duration = currentTmpTranscriptItem!.duration!;
        currentTranscriptItem!.offset = currentTmpTranscriptItem!.offset!;


        saveTranscriptSequen(currentTranscriptItem!,callBack: DataCallBack(
          confirmCallBack: (v) {
            reloadData();
          }
        ));



        globalDuration.value = 0;
        currentSpeaker.value = '';
        finalFromLanguage.value = '';
        tempFromLanguage.value = '';
        fromLanguage.value = '';
        currentTranscriptItem = null;
        currentTmpTranscriptItem = null;
        currentSpeaker.value = result['speaker'];

        fromLanguage.value = fromLanguage.value + result['text'];
        finalFromLanguage.value = fromLanguage.value;

      } else {

        if (finishCount > 6) { //换行.
          finishCount = 0;
          fromLanguage.value = fromLanguage.value + '\n\n';
        }

        fromLanguage.value = fromLanguage.value + result['text'];
        finalFromLanguage.value = fromLanguage.value;

        if (currentTranscriptItem == null) {
          currentTranscriptItem = TranscriptItem(offset: 0,duration: 0);
        }
        globalDuration.value = 0;
        currentTranscriptItem!.text = finalFromLanguage.value;
        currentTranscriptItem!.duration = currentTranscriptItem!.duration! + (result['duration'] as int);
        currentTranscriptItem!.offset = currentTranscriptItem!.offset! + (result['offset'] as int);
        currentTranscriptItem!.speaker = currentSpeaker.value;

      }

    } else {
      currentSpeaker.value = result['speaker'];

      // tempFromLanguage.value = result['text'];

      // 已经finish的字符串+ 未finish的字符串.
      finalFromLanguage.value = fromLanguage.value + result['text'];

      if (currentTmpTranscriptItem == null) {
        currentTmpTranscriptItem = TranscriptItem(duration: 0,offset: 0);
        finalFromLanguage.value = '';
        fromLanguage.value = '';
      }

      currentTmpTranscriptItem!.text = finalFromLanguage.value;
      currentTmpTranscriptItem!.speaker = currentSpeaker.value;
      currentTmpTranscriptItem!.duration = currentTmpTranscriptItem!.duration! + (result['duration'] as int);
      currentTmpTranscriptItem!.offset = currentTmpTranscriptItem!.offset! + (result['offset'] as int);

      globalDuration.value = (currentTmpTranscriptItem!.duration as int);
      // 使用 addPostFrameCallback 确保布局完成后再滚动

      //添加滚动设置.
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _autoScrollToBottom();
      });
    }

    hasTranScript.value = true;

    FlutterOverlayWindow.shareData({
      'finalFromLanguage': finalFromLanguage.value,
      'finalToLanguage': ''
    });
  }


  void reloadData() {
    audioTranscriptSource.clear();
    //查询转写脚本.
    DbDAOHelper().obtainTranscriptsBySessionId(int.parse(sessionId!)).then((transcripts) {
      transcripts.forEach((scriptData) {
        AudioTranscriptDataExtends audioExtends = AudioTranscriptDataExtends(id: scriptData.id, session_id: scriptData.session_id,
            chat_sequence: scriptData.chat_sequence,
            m_id: scriptData.m_id,
            a_text: scriptData.a_text,
            duration: scriptData.duration,
            offset: scriptData.offset,
            speaker: scriptData.speaker,
            create_time: scriptData.create_time,
            update_time: scriptData.update_time);

        audioTranscriptSource.add(audioExtends);
      });


      // 使用 addPostFrameCallback 确保布局完成后再滚动
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _autoScrollToBottom();
      });
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    print('转写页面关闭了..');
     // 写入音频时长.
    if (audioService.recordingSecond != 0) {
         DbDAOHelper().updateSessionLengthyById(int.parse(sessionId!),
             audioService.recordingSecond);
    }


    conversationSequence =  conversationSequence + 1;
    if (currentTranscriptItem != null && currentTranscriptItem!.text!.trim() != '') {
        saveTranscriptSequen(currentTranscriptItem!);

    } else {
        if (currentTmpTranscriptItem != null && currentTmpTranscriptItem!.text != null && currentTmpTranscriptItem!.text!.trim() != '') {
            currentTranscriptItem = currentTmpTranscriptItem;
            saveTranscriptSequen(currentTranscriptItem!);
        }
    }

    if (chatListScrollController !=  null) {
        chatListScrollController.dispose();
    }

    if (audioService.isPlaying.value) {
      audioService.stopRecorder();
    }

    HomeController homeController = Get.find<HomeController>();
    homeController.refreshAudioFiles();


    if (_audioWavetimer != null) {
      _audioWavetimer?.cancel();
    }

    super.onClose();
  }



 void showPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => StatefulBuilder(
          builder: (context, setState) {
            return Obx(()=>SafeArea(child: Container(
              color: Colors.white.withValues(alpha: 0.7),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        Image.asset('assets/images/icon_audio_wave_realtime.png',height: 25.h,),
                        Image.asset('assets/images/icon_audio_wave_realtime.png',height: 25.h,),
                      ],
                    ),
                  ),
                  SizedBox(height: 14.h,),
                  Row(
                    children: [
                      Expanded(child: Container(
                        child: Column(
                          children: [
                            InkWell(
                              onTap: () {
                                if (audioService.recordingSecond != 0) {
                                  DbDAOHelper().updateSessionLengthyById(int.parse(sessionId!),
                                      audioService.recordingSecond);
                                }

                                audioStop = true;
                                audioService.stopRecorder();
                              },
                              child: Stack(
                                children: [
                                  Container(
                                    width: 40.w,
                                    height: 40.h,
                                    decoration: BoxDecoration(
                                        shape: BoxShape.circle,
                                        color: Colors.red
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(left: 13.w,top: 13.h),
                                    width: 12.w,
                                    height: 12.h,
                                    decoration: BoxDecoration(
                                        shape: BoxShape.rectangle,
                                        color: Colors.white
                                    ),
                                  )
                                ],
                              ),
                            ),
                            SizedBox(height: 10.h,),
                            Text('结束录音',style: AppStyleThemeData.HINT_TEXT_STYLE_small,)
                          ],
                        ),
                      ),flex: 1,),
                      Expanded(child: Container(
                        child: Column(
                          children: [
                            InkWell(
                              onTap: () {
                                if (audioStop) {
                                  Tips.showToast('录音已经结束.');
                                  return;
                                }

                                if (audioService.isPlaying.value) {
                                  audioService.pauseRecorder();
                                } else {
                                  audioService.record();
                                }

                                hasTranScript.value = true;
                              },
                              child: audioService.isPlaying.value ? Image.asset('assets/images/icon_play_realtime_btn_running.png',width: 48.w,height: 48.h,):
                              Image.asset('assets/images/icon_record_transcript_pause.png',width: 48.w,height: 48.h,),
                            ),
                            SizedBox(height: 10.h,),
                            Text('${audioService.recordShowSeconds.value}')

                          ],
                        ),
                      ),flex: 1,),
                      Expanded(
                        child: Container(
                          child: Column(
                            children: [
                              Image.asset('assets/images/icon_record_script_bottom_flag.png',width: 24.w,height: 24.h),
                              SizedBox(height: 10.h,),
                              Text('标记',style: AppStyleThemeData.HINT_TEXT_STYLE_small,)
                            ],
                          ),
                        ),
                        flex: 1,
                      )

                    ],
                  )
                ],
              ),
            )));
          },
        ),
        backgroundColor: Colors.white.withValues(alpha: 0.5),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.zero, // 顶部直角
          ),
        ),
        barrierColor: Colors.black.withValues(alpha: 0.1)
    );
  }



  String formatSecondsToTime(int seconds) {
    int minutes = seconds ~/ 60; // 整除得到分钟数
    int remainingSeconds = seconds % 60; // 取余得到剩余秒数

    // 格式化为两位数，不足补零
    String formattedMinutes = minutes.toString().padLeft(2, '0');
    String formattedSeconds = remainingSeconds.toString().padLeft(2, '0');

    return '$formattedMinutes:$formattedSeconds';
  }


  void saveTranscriptSequen(TranscriptItem item, {DataCallBack? callBack}) {
      DbDAOHelper().obtainTranscriptsBySessionIdAndContent(int.parse(sessionId!), item.text??'').then((list) {
        print('list.isEmpty :: ${list.isEmpty}');
        if (list.isEmpty) {

           DbDAOHelper().saveRecordsTranscript(int.parse(sessionId!), conversationSequence, item,callback: callBack);
        }
      });


  }

  String getSpeakerByChatSequence(String chatSequence) {
      String speaker = '';
      audioTranscriptSource.value.forEach((item) {
        if(item.chat_sequence.toString() == chatSequence) {
          speaker = item.speaker;
        }
      });
      return speaker;
  }


  void _autoScrollToBottom() {
    if (chatListScrollController.hasClients) {
      chatListScrollController.animateTo(
        chatListScrollController.position.maxScrollExtent,
        duration: Duration(milliseconds: 300), // 滚动时长
        curve: Curves.easeOut, // 动画曲线
      );
    }
  }


  void simulateAudioData() {
    _audioWavetimer = Timer.periodic(const Duration(milliseconds: 150), (timer) {
      // 生成随机振幅数据，模拟音频输入
      amplitudes.value = List.generate(50, (index) {
        // 生成0-15000之间的随机振幅（模拟16位PCM数据）
        return Random().nextDouble() * (15000 - 5000) + 5000;
      });

    });
  }

  void stopSimulateAudioData() {
    amplitudes.value = [];
    if (_audioWavetimer != null) {
      _audioWavetimer?.cancel();
    }

  }


  void chooseTranscriptLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
    'code': audioService.fromLanguage
    });
    audioService.fromLanguage = languageItem['code'];
    audioService.fromLanFlagDisplay.value = (languageItem['desc'] as String);


    if (audioService.isPlaying.value) {
      audioService.pauseRecorder();
    }

    audioService.reInitWs();
    audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP+NetWorkManager.SPEECH_RECOGNITION}?enableSpeaker=1',
        DataCallBack(
            confirmCallBack: (v) {
              audioService.record();
            },
            sessionCallBack: (params) {
               handlerSessionData(params);
            }
        ));

  }


  void changeEditMode(AudioTranscriptDataExtends scriptData) {
    script_edit_mode.value = true;

    audioTranscriptSource.forEach((dataItem) {
      if (dataItem.id == scriptData.id) {
        dataItem.isChecked = true;
        checkedAudioTranscript = scriptData;
        scriptController.text = checkedAudioTranscript!.a_text;
      } else {
        dataItem.isChecked = false;
      }
    });

  }

  //删除脚本.
  void executeDeleteScript() async {
       if (checkedAudioTranscript != null) {
         int result = await DbDAOHelper().deleteTranscriptsById(checkedAudioTranscript!.id);
         script_edit_mode.value = false;
         reloadData();

       }
  }

  //拷贝脚本.
  void executeCopyScript() async {
    reloadData();
    if (checkedAudioTranscript != null) {
      try {
        await Clipboard.setData(ClipboardData(text: checkedAudioTranscript!.a_text));
        Tips.showToast('已拷贝');

        script_edit_mode.value = false;
      } catch (e) {
        Tips.showToast('拷贝失败');
      }
    }
  }


  //编辑脚本.
  void executeEditScriptList() {
    /*editingStatus.value = !editingStatus.value;
    print('isEditingStatus.value ::: ${editingStatus.value}');
    if (checkedAudioTranscript != null) {
        scriptController.text = checkedAudioTranscript!.a_text;
    }*/
    reloadData();
    script_edit_mode.value = false;
    Get.toNamed(Routes.EDIT_SCRIPTLIST,
     parameters: {
      'sessionId': sessionId!
     });

  }

  //标记脚本.
  void executeTagScript() {

  }

  //保存脚本.
  void executeSaveScript() {
    if (checkedAudioTranscript != null) {
       String editContent =  scriptController.text;
       DbDAOHelper().updateRecordsTranscript(checkedAudioTranscript!.id, editContent).then((result) {
          print('更新结果.  result: ${result}');
          /*script_edit_mode.value = false;
          Tips.showToast('已保存');
          reloadData();*/
       });
    }
  }

}

class AudioTranscriptDataExtends extends AudioTranscriptData {
  bool isChecked = false;
  TextEditingController textEditingController = TextEditingController();
  AudioTranscriptDataExtends({required super.id, required super.session_id,
    required super.chat_sequence, required super.m_id, required super.a_text,
    required super.duration, required super.offset, required super.speaker,
    required super.create_time, required super.update_time});

}